﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;

namespace Bamboo.Helpers
{
    public static class ExpressionExtensions
    {
        public const string CallChainPattern = @"(\w+\.)+\w+";

        public static string GetCallPath<T, R>(this Expression<Func<T, R>> expression)
        {
            string body = expression.Body.ToString();

            return GetCallPathWithoutSubject(body);            
        }

        public static string GetCallPath<T>(this Expression<Action<T>> expression)
        {
            string body = expression.Body.ToString();

            return GetCallPathWithoutSubject(body);
        }

        private static string GetCallPathWithoutSubject(string callPath)
        {
            if (!Regex.IsMatch(callPath, CallChainPattern))
            {
                throw new InvalidOperationException("Expected expression of chain of calls ");
            }

            return callPath.Remove(0, callPath.IndexOf('.') + 1);
        }
    }
}
